package com.lb.shopguide.ui.fragment.boss;

import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterStore;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.entity.MerchantBean;
import com.lb.shopguide.entity.shop.StoreBean;
import com.lb.shopguide.event.boss.AddShopEvent;
import com.lb.shopguide.event.guide.StartBrotherEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.ui.view.NormalTitleBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/12/26.
 */

public class FragmentShopManage extends BaseCommonFragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.ntb)
    NormalTitleBar ntb;
    @BindView(R.id.layout_add_shop)
    RelativeLayout layoutAddShop;
    @BindView(R.id.layout_set_point_percent)
    RelativeLayout layoutPointPercent;
    @BindView(R.id.tv_available_store)
    TextView tvStoreNum;
    @BindView(R.id.tv_already_store)
    TextView tvActualStoreNum;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private AdapterStore mAdapterStore;
    private ArrayList<StoreBean> mStoreList;

    private MerchantBean mMerchantBean;



    public static FragmentShopManage newInstance() {
        FragmentShopManage fragmentShopManage = new FragmentShopManage();
        return fragmentShopManage;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_shop_manage;
    }

    @Override
    public void initData() {
        EventBus.getDefault().register(this);
        mStoreList = new ArrayList<>();
        initRequest();
    }

    @Override
    public void initView() {
        noDataView = LayoutInflater.from(mContext).inflate(R.layout.layout_empty_view_boss, (ViewGroup) mRecyclerView.getParent(), false);
        TextView tvEmpty = noDataView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无门店");
        errorView = LayoutInflater.from(mContext).inflate(R.layout.layout_error_view, (ViewGroup) mRecyclerView.getParent(), false);
        noDataView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });
        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefresh();
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(253, 91, 89));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mAdapterStore = new AdapterStore(R.layout.item_store, mStoreList);
        mRecyclerView.setAdapter(mAdapterStore);
        mAdapterStore.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                StoreBean storeBean = mStoreList.get(position);
                start(FragmentStoreDetail.newInstance(storeBean));
            }
        });

        ntb.setTitleText("门店管理");
        ntb.setLeftImageSrc(R.drawable.iv_back);

        initListener();
    }

    @Override
    public void finishRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        mAdapterStore.loadMoreComplete();
    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    private void initListener() {
        ntb.setOnLeftImageListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
    }

    @Override
    public String getPageTag() {
        return FragmentShopManage.class.getName();
    }


    private void initRequest() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JSONObject jsonObject = JsonUtil.getJsonObjectFromMap(response.getReturnContent());
                    try {
                        String storeNum = jsonObject.getString("storeNum");
                        String actualStoreNum = jsonObject.getString("actualStoreSum");
                        bindStoreNumber(storeNum, actualStoreNum);

                        JSONArray jsonArray = jsonObject.getJSONArray("merStoreList");
                        if (jsonArray.length() != 0) {
                            for (int i = 0; i < jsonArray.length(); i++) {
                                StoreBean storeBean = JsonUtil.getGson().fromJson(jsonArray.getString(i), StoreBean.class);
                                mStoreList.add(storeBean);
                            }
                            mAdapterStore.setNewData(mStoreList);
                        } else {
                            bindEmpty();
                        }
                        finishRefresh();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        ApiMethodBoss.getStoreList(new SimpleLbObserver(listener,otherListener),this, FragmentEvent.DESTROY_VIEW);
    }

    private void bindStoreNumber(String storeNum, String actualStoreNum) {
        tvStoreNum.setText(storeNum);
        tvActualStoreNum.setText(actualStoreNum);
    }

    @OnClick(R.id.layout_set_point_percent)
    void pointPercentClick(){
        EventBus.getDefault().post(new StartBrotherEvent(FragmentPointPercent.newInstance()));
    }

    @OnClick(R.id.layout_add_shop)
    void addShop(){
        EventBus.getDefault().post(new StartBrotherEvent(FragmentAddEditShop.newInstance()));
    }

    public void refresh() {
        mStoreList = new ArrayList<>();
        initRequest();
    }

    @Subscribe
    public void onAddShop(AddShopEvent event) {
        refresh();
    }

    private void bindEmpty() {
        mStoreList.clear();
        mAdapterStore.setNewData(mStoreList);

        mNoData = true;
        onRefresh();
    }

    @Override
    public void onRefresh() {
        mAdapterStore.setEnableLoadMore(false);
        if (mError) {
            mAdapterStore.setEmptyView(errorView);
            mError = false;
        } else {
            if (mNoData) {
                mAdapterStore.setEmptyView(noDataView);
                mNoData = false;
            } else {
                refresh();
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
